package cn.bigfire.wzdj.util.sign;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import cn.bigfire.wzdj.pojo.httpVo.Token2GameUser;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class WZDJSign {

    public static HashMap<String,String> headers(){
        HashMap<String,String> headers = new HashMap<>();
        headers.put("Host","sdkapi.hnys68.cn");
        headers.put("xweb_xhr","1");
        headers.put("Content-Type","application/json");
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c11)XWEB/11275");
        headers.put("Referer","https://servicewechat.com/wx71702c33334e92bd/13/page-frame.html");
        headers.put("Accept-Encoding","gzip, deflate, br");
        headers.put("Accept-Language","zh-CN,zh;q=0.9");
        headers.put("Accept", "*/*");
        return headers;
    }

    public static HashMap<String,String> paramMap(String timestamp,String uuid){
        HashMap<String,String> paramMap = new HashMap<>();
        paramMap.put("appId","2074");
        paramMap.put("pid","2074010");
        paramMap.put("clientType","5");
        paramMap.put("encryptflag","0");
        paramMap.put("uuid",uuid);
        paramMap.put("timestamp", timestamp);
        paramMap.put("version", "v2");
        paramMap.put("subUserType", "1051");
        return paramMap;
    }

    private static HashMap<String,String> lowerCaseMap(HashMap<String,String> originalMap){
        HashMap<String, String> lowerCaseMap = new HashMap<>();
        for (Map.Entry<String, String> entry : originalMap.entrySet()) {
            lowerCaseMap.put(entry.getKey().toLowerCase(), entry.getValue());
        }
        return lowerCaseMap;
    }

    public static String registerLoginAccessToken(String code) {
        String openAppId = "wx71702c33334e92bd";//小程序 王者对决唯一
        String uuid = "wx-ol9sW7RiscrRqWOQ1wPrQSP0NKEM";//用户wx- openId

        String secret_key = "d01474ee9670540687a7f2464a570abc";//不变key
        String tlp = "https://sdkapi.hnys68.cn/api/sdk/v2/accounts/action/registerlogin/openuser-mp?appId=2074&pid=2074010&clientType=5&encryptflag=0&uuid=%s&timestamp=%s&version=v2&subUserType=1051&sign=%s";
        String timestamp = String.valueOf(System.currentTimeMillis()).substring(0, 10);//13位截取前10位即可
        HashMap<String, String> paramMap = lowerCaseMap(paramMap(timestamp, uuid));
        String body = "{\"openAppId\":\"" + openAppId + "\",\"userType\":105,\"token\":\"" + code + "\",\"formAdID\":\"\",\"fromRSID\":\"\",\"adInfo\":\"{\\\"pid\\\":2074010}\",\"adCache\":\"\"}";
        paramMap.put("body", body);
        TreeMap<String, String> sortMap = MapUtil.sort(paramMap);
        String str = MapUtil.sortJoin(sortMap, "&", "=", true);
        HMac hMac = SecureUtil.hmacSha256(secret_key);
        String sign = hMac.digestHex(str);
        String url =  String.format(tlp, uuid, timestamp, sign);
        HttpRequest post = HttpUtil.createPost(url);
        post.addHeaders(headers());
        post.body(body);

        String result = post.execute().body();
        if (JSONUtil.isTypeJSONObject(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            log.info(jsonObject.toJSONString());
            if (jsonObject.containsKey("result")) {
                JSONObject dataObject = jsonObject.getJSONObject("result");



                return dataObject.getString("accessToken");
            }
        }
        return "";
    }
    public static Token2GameUser decodeObj(String accessToken){
        String[] tokenArr = accessToken.split("\\.");
        String decode = Base64.decodeStr(tokenArr[1]);//取中间一段进行解码操作
        if (JSONUtil.isTypeJSONObject(decode)) {
            return JSONObject.parseObject(decode, Token2GameUser.class);
        }
        return null;
    }

    public static void main(String[] args) {
//        String code = "0f1FFl2w3Vd7T33fQh4w3tEjkp3FFl2X";//唯一
//        String accessToken = registerLoginAccessToken(code);
//        log.info(accessToken);

//        String url = "http://101.34.7.208:8081/api/Login/GetQR";
//        HttpRequest post = HttpUtil.createPost(url);
//        post.header("Content-Type", "application/json");
//        post.body("{}");
//        String body = post.execute().body();
//        if (JSONUtil.isTypeJSONObject(body)) {
//            JSONObject jsonObject = JSONObject.parseObject(body);
//            if (jsonObject.getIntValue("Code")==1){
//                JSONObject dataObject = jsonObject.getJSONObject("Data");
//                String qrBase64 = dataObject.getString("QrBase64");
//                String uuid = dataObject.getString("Uuid");
//            }
//        }
//        log.info(body);
    }


    @Test
    @SneakyThrows
    public void test() {
        String str = "eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMzY2OTc3NDI2IiwiVVVJRCI6Ind4LW9sOXNXN1Jpc2NyUnFXT1Exd1ByUVNQME5LRU0iLCJHYW1lSWQiOiIyMDc0IiwiVXNlcklkIjoiMzY2OTc3NDI2IiwiVXNlck5hbWUiOiJiY2E1MzA2MDc1IiwiSXNQYXNzV29yZCI6InRydWUiLCJJc0JpbmRNb2JpbGUiOiJmYWxzZSIsIlJlYWxOYW1lU3RhdHVzIjoiMSIsIk5vbmVLaWQiOiIxIiwiSXNWaXNpdG9yIjoiZmFsc2UiLCJJc05ld1VzZXIiOiJmYWxzZSIsIlBpZCI6IjIwNzQwMTAiLCJDbGllbnRUeXBlIjoiNSIsIlB3ZGNvZGUiOiItMTI1NjYyMTU4OCIsIklkQ2FyZExvY2tlZFN0YXR1cyI6IjAiLCJJZENhcmRMb2NrZWRNc2ciOiIiLCJPcGVuSWQiOiJvbDlzVzdSaXNjclJxV09RMXdQclFTUDBOS0VNIiwiSGFzTmV3VXNlciI6IjAiLCJBZGluZm8iOiIiLCJSc2lkIjoiIiwiQWRSZXNldEZsYWciOiIwIiwiTGFzdExvZ2luIjoiMTczMTgyOTQ0MyIsIm5iZiI6MTczMTgyOTc3OCwiZXhwIjoxNzMyMDg4OTc4LCJpc3MiOiJxMS5jb20iLCJhdWQiOiJFdmVyeW9uZSJ9";
        String decode = Base64.decodeStr(str);
        System.out.println(decode);
    }


}
